#include"Sort.h"

void Print(int* a, int n)
{
	for (int i = 0; i < n; i++)
	{
		printf("%d ", a[i]);
	}
	printf("\n");
}

void Swap(int* a, int* b)
{
	int temp = *a;
	*a = *b;
	*b = temp;
}

void BubbleSort(int* a, int n)
{
	for (int j = 0; j < n - 1; j++)
	{
		for (int i = 0; i < n -1 - j; i++)
		{
			if (a[i] > a[i + 1])
			{
				Swap(&a[i], &a[i + 1]);
			}
		}
	}
}

void InsertSort(int* a, int n)
{
	for (int i = 0; i < n - 1; i++)
	{
		int end = i;
		int temp = a[end + 1];
		while (end >= 0)
		{
			if (temp < a[end])
			{
				a[end + 1] = a[end];
				--end;
			}
			else
			{
				a[end + 1] = temp;
				break;
			}
		}
		// 要插入的数 end < 0 
		a[end + 1] = temp;
	}
	
}

void ShellSort(int* a, int n)
{
	int gap = n;
	while (gap > 1)
	{
		gap /= 2;
		
		for (int i = 0; i < n - gap; i++)
		{
			int end = i;
			int temp = a[end + gap];
			while (end >= 0)
			{
				if (temp < a[end])
				{
					a[end + gap] = a[end];
					end -= gap;
				}
				else
				{
					a[end + gap] = temp;
					break;
				}
			}
			a[end + gap] = temp;
		}
	}
}

void AdjustDown(int* a, int n, int parent)
{
	int child = parent * 2 + 1;
	while (child < n)
	{
		if (child + 1 < n && a[child + 1] > a[child])
		{
			++child;
		}

		if (a[child] > a[parent])
		{
			Swap(&a[child], &a[parent]);
			parent = child;
			child = parent * 2 + 1;     
		}
		else
		{
			break;
		}
	}
}

void HeapSort(int* a, int n)
{
	// 直接插入建堆 O(N)  
	for (int i = (n - 1 - 1) / 2; i >= 0; --i)
	{
		AdjustDown(a, n, i);
	}

	// 升序建大堆
	// O(N*logN)
	int end = n - 1;
	while (end > 0)
	{
		Swap(&a[0], &a[end]);
		AdjustDown(a, end, 0);
		--end;
	}
}


void SelectSort(int* a, int n)
{
	int begin = 0, end = n - 1;

	while (begin < end)
	{
		int min = begin, max = begin;

		for (int i = begin + 1; i <= end; i++)
		{
			if (a[i] < a[min])
			{
				min = i;
			}

			if (a[i] > a[max])
			{
				max = i;
			}
		}
		Swap(&a[begin], &a[min]);
		if (max == begin)
		{
			max = min;
		}
		Swap(&a[end], &a[max]);
		++begin;
		--end;
	}
}

// 三数取中


void QuickSort(int* a, int left, int right)
{
	if (left >= right)// 最小子问题得结束条件
		return;

	int begin = left, end = right;
	int keyi = left;
	
	while (left < right)
	{
		// right先走， 找比 key 小
		// left < right 防止right一直往前走（越界）
		// 若没有“=” 相等的数，就会一直在交换，造成死循环
		while (left < right && a[right] >= a[keyi])
		{
			--right;
		}

		//  找比key大
		while (left < right && a[left] <= a[keyi])
		{
			++left;
		}
		// 各自都找到了,进行交换
		Swap(&a[left], &a[right]);
	}
	// 相遇，与key交换
	Swap(&a[left], &a[keyi]);
	keyi = left;

	// [begin, keyi - 1] keyi [keyi+1, end]
	PartSort(a, begin, keyi - 1);
	PartSort(a, keyi + 1, end);
}